//---------------------------------------------------------------------
// Author: jachymko
//
// Description: Wmi class names cache
//
// Creation Date: Jan 8, 2007
//---------------------------------------------------------------------

using System;
using System.Management;
using System.Collections.Generic;
using System.Text;

namespace BGShell.PowerShell.TabExpansion.Caches
{
    internal sealed class WmiClassCache : TabExpansionCache
    {
        private readonly List<String> _classes = new List<string>();

        private WmiClassCache()
        {
        }

        internal override void OnInitialize()
        {
            var path = new ManagementPath();
            var scope = new ManagementScope(@"\\.\root\cimv2");

            using (var root = new ManagementClass(scope, path, new ObjectGetOptions()))
            {
                var options = new EnumerationOptions()
                {
                    EnumerateDeep = true,
                };

                foreach (var obj in root.GetSubclasses(options))
                {
                    if (Stopped)
                    {
                        break;
                    }

                    using (obj)
                    {
                        _classes.Add(obj.ClassPath.ClassName);
                    }
                }
            }
        }

        public IEnumerable<String> Expand(string str)
        {
            Instance.EnsureInitialized();

            foreach (string cls in _classes)
            {
                if (cls.StartsWith(str, StringComparison.OrdinalIgnoreCase))
                    yield return cls;
            }
        }

        public static readonly WmiClassCache Instance = new WmiClassCache();
    }
}
